'use strict';

const Service = require('egg').Service;
const { stateKeys } = require('../core/base_mongo_model');
const { BANNER_LIST_CATCE_KEY, BANNER_LIST_DUSTBIN_CATCE_KEY } = require('../../config/redisKey');

class BannerService extends Service {
  /**
   * 获取所有数据
   */
  async all() {
    const { type } = this.ctx.query
    if (type == 'redis') {
      return this.ctx.getCache(BANNER_LIST_CATCE_KEY, async () => {
        return await this.ctx.model.Banner.find({ $or: [
            { stateKey: stateKeys.NORMAL },
            { stateKey: { $exists: false } },
          ] }).sort({ index: 1 }).exec();
      }, true);
    } else if (type == 'file') {
      return  await this.ctx.getJsonLocalCatch(BANNER_LIST_CATCE_KEY, async () => {
        return await this.ctx.model.Banner.find({ $or: [
            { stateKey: stateKeys.NORMAL },
            { stateKey: { $exists: false } },
          ] }).sort({ index: 1 }).exec();
      })
    }
    return await this.ctx.model.Banner.find({ $or: [
        { stateKey: stateKeys.NORMAL },
        { stateKey: { $exists: false } },
      ] }).sort({ index: 1 }).exec();
  }

  /**
   * 创建Banner
   */
  async create() {
    const { Banner } = this.ctx.model;
    // await this.ctx.clearCache(BANNER_LIST_CATCE_KEY)
    await this.ctx.clearJsonLocalCatch(BANNER_LIST_CATCE_KEY)
    return await new Banner(this.ctx.w_body()).save();
  }

  /**
   * 删除数据
   */
  async destroy() {
    const { Banner } = this.ctx.model;
    await this.ctx.clearCache(BANNER_LIST_DUSTBIN_CATCE_KEY)
    await this.ctx.clearJsonLocalCatch(BANNER_LIST_CATCE_KEY)
    return await Banner.removeBanner(this.ctx.params.id);
  }

  /**
   * 更新数据
   */
  async update() {
    const { Banner } = this.ctx.model;
    const { id } = this.ctx.params
    // await this.ctx.clearCache(BANNER_LIST_CATCE_KEY)
    await this.ctx.clearJsonLocalCatch(BANNER_LIST_CATCE_KEY)
    return await Banner.updateBanner(id, this.ctx.w_body());
  }

  /**
   * 获取回收站列表
   */
  async dustbinList() {
    return this.ctx.getCache(BANNER_LIST_DUSTBIN_CATCE_KEY, async () => {
      return await this.ctx.model.Banner.find({ $or: [
        { stateKey: stateKeys.DUSTBIN },
      ] }).sort({ index: 1 }).exec();
    });
  }
  /**
   * 从回收站还原
   */
  async dustbinRestore() {
    const { Banner } = this.ctx.model;
    await this.ctx.clearCache(BANNER_LIST_DUSTBIN_CATCE_KEY)
    await this.ctx.clearJsonLocalCatch(BANNER_LIST_CATCE_KEY)
    const { id } = this.ctx.params;
    return await Banner.dustbinRestore(id);
  }
  /**
   * 从回收站删除数据
   */
  async dustbinDelete() {
    const { Banner } = this.ctx.model;
    await this.ctx.clearCache(BANNER_LIST_DUSTBIN_CATCE_KEY)
    return await Banner.removeBanner(this.ctx.params.id, true);
  }
}

module.exports = BannerService;
